<template>
	<div class="llm-container">
		<el-form-item label="意图点">
			<p class="llmSetting add" v-if="!showDetail">
				<el-button class="" @click="addIntentionBranch" v-if="isShowIntention && !showDetail && intentPoints.length === 0">添加意图点</el-button>
			</p>
		</el-form-item>
		<template v-if="intentPoints.length !== 0">
			<div class="answer" v-for="(item, index) in intentPoints" :key="index">
				<img @click="deleteIntention(index)" class="del-btn" :src="deleteImage" v-show="!showDetail" />
				<el-form-item :label="`意图点${index + 1} `" :prop="`${prop}.${index}.answerIntention`" :rules="rules.answerIntention">
					<el-input
						v-model="item.answerIntention"
						:disabled="showDetail"
						@input="e => (item.answerIntention = validForbid(e))"
						maxlength="140"
						placeholder="请输入意图点"
						@change="onChange('intention.' + index + '.answerIntention')"
						style="width: 260px"
					>
					</el-input>
				</el-form-item>

				<div v-for="(itemInfo, selectIndex) in item.additionalInformation" :key="selectIndex" class="additionalInformation-item">
					<el-form-item :label="`待补充信息`" :prop="`${prop}.${index}.additionalInformation.${selectIndex}.paramKey`" :rules="rules.additionalInformation.paramKey">
						<el-input
							v-model="itemInfo.paramKey"
							:disabled="showDetail"
							@input="e => (itemInfo.paramKey = validForbid(e))"
							maxlength="140"
							placeholder="待补充信息"
							style="width: 110px; margin-right: 10px"
						>
						</el-input>
					</el-form-item>
					<div class="clickable-container" @click="selectVariable(index, selectIndex)">
						<el-form-item label="" :prop="`${prop}.${index}.additionalInformation.${selectIndex}.variable`" :rules="rules.additionalInformation.variable">
							<el-input v-model="itemInfo.variable" :readonly="true" style="width: 180px" placeholder="绑定变量"> </el-input>
						</el-form-item>
					</div>
					<div class="del-paramter" @click="deleteParameter(index, selectIndex)" v-show="!showDetail">
						<img :src="deleteImage" class="" />
					</div>
				</div>
				<div class="add-paramter" v-if="!showDetail">
					<el-button class="custom-btn" @click="addParameter(index)" v-show="item.additionalInformation.length < 16 && showAddPrameter">添加待补充信息</el-button>
				</div>
				<AiSpeak
					:rules="rules.answerSpeak"
					:variableIcon="true"
					:required="false"
					:disabled="showDetail"
					:value="item.answerSpeak"
					:validateStatus="item.answerSpeakValidate"
					:video="item.video"
					@clearVideo="clearVideo(index)"
					:textArea="false"
					:label="'AI说'"
					@input="(e, val) => input(e, val, index)"
					placeholder="请编辑AI客服播报的话术"
					@showVideoTable="showVideoTable(index)"
					@onAddVariable="onAddVariable(index)"
					:id="'answerSpeak' + index"
					:prop="`${prop}_${index}_answerSpeak`"
					@change="onChange('intention_' + index + '_answerSpeak')"
					style="width: 480px"
				/>
				<el-form-item label="下一步" :prop="`${prop}.${index}.nextStepsAnswer`" class="nextBotton" required="true" :rules="rules.nextStepsAnswer">
					<el-select
						v-model="item.nextStepsAnswer"
						:disabled="showDetail"
						placeholder="下一步操作"
						@change="onChange('intention.' + index + '.nextStepsAnswer')"
						class="intention-select"
						id="intention-select"
					>
						<el-option v-for="item in nextStepOption" :key="item.value" :label="item.taskName" :value="item.taskId"> </el-option>
					</el-select>
				</el-form-item>
				<div class="btn" v-if="!showDetail">
					<img @click="addIntention" class="add-btn" :src="insertImage" v-if="isActiveIcon && index === intentPoints.length - 1 && index !== 5" />
				</div>
				<VideoTable
					v-if="tableVideoDialog"
					:tableVideoDialog="tableVideoDialog"
					:videoType="tableVideoType"
					:videoSlect="selectVideoIndex[inputCurrIndex]"
					@ok="sureVideoData"
					@cancel="cancelVideoData"
					:showDetail="showDetail"
				/>
				<!-- 用户变量 -->
				<UserAttribute
					v-if="isShowUserAttribute"
					:dialogVisible="isShowUserAttribute"
					:hiddenBusinessData="hiddenBusinessData"
					@on-ok="onChosseUserAttribute"
					@on-cancel="onCloseUserAttribute"
					:selectId="selectVariableId"
				/>
			</div>
		</template>
	</div>
</template>

<script>
import AiSpeak from '../AiSpeak/index.vue';
import UserAttribute from './UserAttribute.vue';
import VideoTable from '@/views/components/VideoTable.vue';
import { insertStr } from '@/utils/tool';
import delGroupImg from '@/assets/img/icon/del_group.png';
import addGroupImg from '@/assets/img/icon/add_group.png';
import aivideoErrorImg from '@bpmn/assets/img/aivideoError.png';
import aivideoImg from '@bpmn/assets/img/aivideo.png';
import AIWorkflow from '@/modules/workFlow';
export default {
	name: 'LLM',
	components: {
		AiSpeak,
		VideoTable,
		UserAttribute
	},
	props: {
		nextStepOption: {
			type: Array,
			default: () => [],
			required: true
		},
		prop: {
			type: String,
			default: () => ''
		},
		value: {
			type: Array,
			required: true,
			default: () => []
		},

		showDetail: {
			type: Boolean,
			default: () => false
		},
		videoIcon: {
			type: String,
			default: () => ''
		}
	},
	data() {
		const vaildateRepeats = (rule, value, callback) => {
			let arr = this.intentPoints.filter(item => item.answerIntention === value);
			if (arr.length > 1) {
				return callback(new Error('该意图点已被使用，请输入别的意图点'));
			}
			return callback();
		};
		const vaildateParamKey = (rule, value, callback) => {
			// field: "intentPoints.0.additionalInformation.1.paramKey"
			// console.log('vaildateParamKey value', rule, value, callback);
			let index = rule.field.split('.')[1];
			let selectIndex = rule.field.split('.')[3];
			this.intentPoints[index].additionalInformation[selectIndex].do.data = value;
			let arr = this.intentPoints[index].additionalInformation.filter(item => item.paramKey === value);
			if (arr.length > 1) {
				return callback(new Error('该补充信息已被使用！'));
			}
			return callback();
		};

		const vaildateBindVariable = (rule, value, callback) => {
			let index = rule.field.split('.')[1];
			let arr = this.intentPoints[index].additionalInformation.filter(item => item.variable === value);
			if (arr.length > 1) {
				return callback(new Error('该变量已经被绑定！'));
			}
			return callback();
		};
		const vaildateVideo = (rule, value, callback) => {
			// console.log('vaildateVideo ###', rule, value, callback);
			let index = rule.field.split('_')[1];
			let item = this.intentPoints[index];
			if (item.answerSpeak && !item.video) {
				item.answerSpeakValidate = false;
				// this.intentPoints[index].answerSpeakValidate = false;
				// 手动触发更新
				this.$forceUpdate();
				return callback(new Error('请选择播报视频'));
			}
			// this.intentPoints[index].answerSpeakValidate = true;
			item.answerSpeakValidate = true;
			// 手动触发更新
			this.$forceUpdate();
			return callback();
		};

		return {
			intentLib: [], // 意图库列表
			intentionDotList: [], // 意图点列表
			intentLibName: '',
			intentPoints: [],
			isShowAnswerYes: false, // 回答分支
			isActiveIcon: true, // icon图标显示隐藏
			isShowIntention: true,
			isShowUserAttribute: false,
			deleteImage: delGroupImg,
			insertImage: addGroupImg,
			errorVideo: aivideoErrorImg,
			videoSelectIcon: aivideoImg,

			// currIndex: null,
			currVariableindex: null,
			inputCurrIndex: null,
			tableVideoDialog: false,

			// 补充信息绑定变量
			bindVariableIntentIndex: null, // 当前意图点索引
			bindVariableSelectIndex: null, // 当前选择索引
			selectVariableId: '', // 当前选择变量id

			// 验证规则校验
			selectVideoIndex: [],
			showAddPrameter: false, // 显示增加补充变量功能
			hiddenBusinessData: false, // 因此变量选择中的业务信息
			rules: {
				nextStepsAnswer: [
					{
						required: true,
						message: '请选择下一步操作',
						trigger: 'change'
					}
				],
				answerIntention: [
					{
						required: true,
						message: '请输入意图点',
						trigger: ['blur', 'change']
					},
					{ validator: vaildateRepeats, trigger: ['blur', 'change'] }
				],
				answerSpeak: [{ validator: vaildateVideo, trigger: ['blur', 'change'] }],
				additionalInformation: {
					paramKey: [
						{
							required: true,
							message: '请输入待补充信息',
							trigger: ['blur', 'change']
						},
						{ validator: vaildateParamKey, trigger: ['blur', 'change'] }
					],
					variable: [
						{
							required: true,
							message: '请绑定变量',
							trigger: ['blur', 'change']
						},
						{ validator: vaildateBindVariable, trigger: ['blur', 'change'] }
					]
				}
			}
		};
	},
	watch: {
		value(val) {
			console.log('意图点', val);
			this.intentPoints = val;
		}
	},
	mounted() {
		this.updateVideo = this.sureVideoData;
		console.log('llm prop', this.prop);
		const { videoType, audioType } = AIWorkflow.getRobotProperty();
		// video-switching tts  real-time-fitting
		console.log('##videoType', videoType, audioType);
		if (videoType === 'real-time-fitting' || (videoType === 'video-switching' && audioType === 'tts')) {
			this.showAddPrameter = true;
		}
		this.intentPoints = this.value;
	},
	methods: {
		// 待补充信息绑定变量
		selectVariable(index, selectIndex) {
			console.log('selectVariable', index, selectIndex);
			this.isShowUserAttribute = true;
			this.bindVariableIntentIndex = index;
			this.bindVariableSelectIndex = selectIndex;
			this.selectVariableId = this.intentPoints[index].additionalInformation[selectIndex].additionalInfovariable.id;
			this.hiddenBusinessData = true;
		},

		// 删除待补充信息
		deleteParameter(index, selectIndex) {
			console.log('deleteParameter', index, selectIndex);
			this.intentPoints[index].additionalInformation.splice(selectIndex, 1);
		},
		// 添加待补充信息
		addParameter(index) {
			console.log('addParameter', index);
			this.intentPoints[index].additionalInformation.push({
				do: {
					data: ''
				},
				additionalInfovariable: {
					id: '',
					url: '',
					name: '',
					type: '',
					method: '',
					params: [],
					roleId: '',
					initMode: '',
					linkedKey: '',
					dataMasking: {}
				},
				paramKey: '',
				variable: ''
			});
		},

		// 新增特定意图分支
		addIntentionBranch() {
			this.isShowAnswerYes = true;
			this.isShowIntention = false;
			/**
			 * let option = {};
			option.answerIntention = item.key; // 意图点
			option.answerSpeak = item.after ? item.do?.data : ''; // ai说
			option.video = item.after ? item.do.video : tts ? item.do.video : null; // video模式视频
			option.nextStepsAnswer = item.after ? item.after.id : item.do.id; // 下一步
			options.additionalInformation = item.additionalInformation; // 待补充信息绑定的变量
			// option.name = item.name;
			option.answerSpeakVariables = item.after ? item.do.variables : tts ? item.do.variables : [];
			 */
			if (this.intentPoints.length === 0) {
				let intention = {
					answerIntention: '', // 意图点
					answerSpeak: '', // ai说
					nextStepsAnswer: '', // 下一步
					answerSpeakVariableId: '', // ai说绑定的变量id
					answerSpeakVariables: [],
					video: '', // video模式视频
					answerSpeakValidate: true,
					additionalInformation: [] // 待补充信息绑定的变量
				};
				this.intentPoints.push(intention);
				this.$emit('input', this.prop, this.intentPoints);
			}
		},
		// + 号icon 添加回答分支
		addIntention() {
			let intention = {
				answerIntention: '', // 意图点
				answerSpeak: '', // ai说
				nextStepsAnswer: '', // 下一步
				answerSpeakVariableId: '', // ai说绑定的变量id
				answerSpeakVariables: [],
				video: '', // video模式视频
				answerSpeakValidate: true,
				additionalInformation: [] // 待补充信息绑定的变量
			};
			this.intentPoints.push(intention);
			this.$emit('input', this.prop, this.intentPoints);
		},
		// 删除意图分支
		deleteIntention(index) {
			if (this.intentPoints.length - 1 === 0) {
				this.isShowIntention = true;
				this.isShowAnswerYes = false;
			}
			this.intentPoints.splice(index, 1);
			this.$emit('input', this.prop, this.intentPoints);
		},
		onChange() {},
		onChosseUserAttribute(data, businessData) {
			console.log('onChosseUserAttribute data', data, businessData);
			if (this.bindVariableIntentIndex !== null) {
				console.log('this.bindVariableIntentIndex', this.bindVariableIntentIndex);
				let variable = '';
				if (data && data.bizscenario_role && data.bizscenario_role.name) {
					variable = `{{客户信息_${data.bizscenario_role.name}_${data.name}_${data.id}}}`;
				} else {
					variable = `{{业务信息_${businessData.name}_${businessData.id}}}`;
				}
				this.intentPoints[this.bindVariableIntentIndex].additionalInformation[this.bindVariableSelectIndex].variable = variable;
				this.intentPoints[this.bindVariableIntentIndex].additionalInformation[this.bindVariableSelectIndex].additionalInfovariable = data || businessData;
				this.isShowUserAttribute = false;
				this.bindVariableIntentIndex = null;
				this.bindVariableSelectIndex = null;
				this.hiddenBusinessData = false;
				return;
			}

			// const parentNode = document.getElementById(`answerSpeak${this.currVariableindex}`);
			// const wordsDom = parentNode.getElementsByClassName('el-textarea__inner');
			let wordsDom = document.getElementById(`${this.prop}_${this.currVariableindex}_answerSpeak`);
			if (!wordsDom) {
				wordsDom = document.getElementById(`${this.prop}_${this.currVariableindex}_answerSpeaktextarea`);
			}
			console.log(wordsDom);
			let variable = '';
			if (data && data.bizscenario_role && data.bizscenario_role.name) {
				variable = `{{客户信息_${data.bizscenario_role.name}_${data.name}_${data.id}}}`;
				this.intentPoints[this.currVariableindex].answerSpeakVariableId = data.id;
				this.intentPoints[this.currVariableindex].answerSpeakVariables.push(data);
			} else {
				variable = `{{业务信息_${businessData.name}_${businessData.id}}}`;
				this.intentPoints[this.currVariableindex].answerSpeakVariableId = businessData.id;
				this.intentPoints[this.currVariableindex].answerSpeakVariables.push(businessData);
			}
			this.intentPoints[this.currVariableindex].answerSpeak = insertStr(this.intentPoints[this.currVariableindex].answerSpeak, wordsDom, variable);

			this.inputCurrIndex = this.currVariableindex;
			this.$emit('input', this.prop, this.intentPoints);
			this.isShowUserAttribute = false;
			this.bindVariableIntentIndex = null;
			this.bindVariableSelectIndex = null;
			this.hiddenBusinessData = false;
		},
		showVideoTable(index) {
			this.inputCurrIndex = index;
			this.tableVideoDialog = true;
			console.log(this.intentPoints);
		},
		cancelVideoData() {
			this.tableVideoDialog = false;
		},
		sureVideoData(id, video) {
			this.intentPoints[this.inputCurrIndex].video = video;
			this.tableVideoDialog = false;
			this.selectVideoIndex[this.inputCurrIndex] = id;
		},
		input(prop, val, index) {
			this.intentPoints[index].answerSpeak = val;
			this.inputCurrIndex = index;
			this.$emit('input', this.prop, this.intentPoints);
		},
		clearVideo(index) {
			console.log(this.intentPoints);
			this.intentPoints[index].video = '';
			this.selectVideoIndex[index] = null;
			this.$emit('input', this.prop, this.intentPoints);
		},
		onAddVariable(index) {
			this.isShowUserAttribute = true;
			this.currVariableindex = index;
		},

		onCloseUserAttribute() {
			this.isShowUserAttribute = false;
			this.bindVariableIntentIndex = null;
			this.bindVariableSelectIndex = null;
			this.hiddenBusinessData = false;
		}
	}
};
</script>

<style lang="less" scoped>
/deep/ .el-form-item__content {
	margin-left: 0px !important;
}

.llmSetting {
	margin-top: 30px;
	.el-button {
		background-color: #fff;
		border: 1px solid #6384fe;
		color: #6384fe;
	}
}
.add {
	position: relative;
	text-align: left;
	left: 0;
	top: 0;
	padding-top: 10px;
	padding-bottom: 10px;
}
.answer {
	// padding-top: 20px;
	width: calc(100% - 50px);
	// height: 168px;
	background-color: #f9f9f9;
	margin-top: 15px;
	position: relative;
	padding-bottom: 5px;
	.checkbox {
		position: absolute;
		right: 8px;
		top: 28px;
	}
	.intention-select {
		width: 306px;
	}
	.el-input {
		width: 260px;
	}
}

.btn {
	position: relative;
}
.add-btn {
	position: absolute;
	top: -15px;
	right: -30px;
}
.del-btn {
	margin-left: calc(100% + 10px);
}
.del-paramter {
	width: 14px;
	height: 14px;
	margin-left: 3px;
	margin-top: 9px;
}
/* 自定义按钮样式 */
.custom-btn {
	/* 基础样式 */
	border: none !important; /* 去除边框 */
	padding-left: 24px !important; /* 图标预留空间 */
	background: #409eff !important; /* 保持Element-UI的主色 */
	color: white !important;

	/* 自定义+图标 */
	position: relative;
}

.custom-btn::before {
	content: '+'; /* 图标内容 */
	position: absolute;
	left: 12px; /* 左侧间距 */
	top: 50%;
	transform: translateY(-50%);
	font-size: 16px; /* 图标大小 */
	font-weight: bold;
	color: white; /* 图标颜色 */
	margin-right: 8px; /* 图标与文字间距 */
}

/* 去除默认边框和悬停效果 */
.custom-btn.el-button {
	border-radius: 4px !important; /* 保留圆角 */
	box-shadow: none !important; /* 去除阴影 */
}

.custom-btn.el-button:hover,
.custom-btn.el-button:focus {
	border: none !important; /* 去除悬停边框 */
	background: #66b1ff !important; /* 悬停颜色 */
	box-shadow: none !important;
}

/* 禁用状态样式 */
.custom-btn.el-button:disabled {
	background: #ebeef5 !important; /* 禁用背景色 */
	color: #c0c4cc !important; /* 禁用文字色 */
}

.custom-btn.el-button:disabled::before {
	color: #c0c4cc !important; /* 禁用图标色 */
}
.add-paramter {
	width: 100%;
	// background: red;
	margin: 0 auto;
	display: flex;
	flex-direction: row;
	justify-content: center;
	margin-bottom: 20px;
}
.additionalInformation-item {
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: flex-start;
	// background: red;
	height: 60px;
}
</style>
